require(["dojo", "dojo/_base/xhr", "dojo/on", "dojo/dom", "dojo/dom-class", 
         "dojo/parser", "dojo/query", "dojo/dom-attr", "dojo/dom-style", "dojo/dom-construct", 
         "dojo/_base/connect", "dojox/gfx", "dojox/gfx/canvas", "dojox/gfx/matrix", "dojo/_base/lang", 
         "dojo/_base/event", "dojo/_base/connect", "dojo/dnd/Moveable", "dojox/gfx/move", 
         "dojo/NodeList-traverse", "dojo/NodeList-manipulate", "dojo/domReady!"], 
         function(dojo, xhr, on, dom, domClass, parser, query, domAttr, domStyle, construct, connect, gfx, canvas, matrix, lang, _event, connect) {
    
    var currentZ = 1;
    createChatWindow = function(obj) {
        var xs = 10;
        var ys = 10;
        construct.create("div", {
            id: obj.svgId
        }, "basediv");
        domStyle.set(obj.svgId, {
            "z-index": ++currentZ,
            "position": "absolute",
            "left": obj.currentLeft + "px"
        });

        var container = dojo.byId(obj.svgId);

        var chatSurface = dojox.gfx.createSurface(container, 260, 300);
        // this is actually a rectangle
        var chatCanvas = null;
        chatGroup = chatSurface.createGroup();

        var chatWindowBody = chatGroup.createRect({
            x: xs + 30,
            y: ys,
            height: 210,
            width: 250
        });
        var statusBlock = chatGroup.createRect({
            x: xs + 100,
            y: ys + 240,
            height: 30,
            width: 150
        });
        var outerStroke = chatGroup.createPolyline([
            {
            x: xs,
            y: ys},
        {
            x: xs + 250,
            y: ys},
        {
            x: xs + 250,
            y: ys + 260},
        {
            x: xs + 100,
            y: ys + 260},
        {
            x: xs + 100,
            y: ys + 240},
        {
            x: xs,
            y: ys + 240},
        {
            x: xs,
            y: ys}
        ]).setStroke({
            join: "round",
            width: 1,
            cap: "round",
            color: "#d0d0d0"
        }).setFill("white");
        var headerRect = chatGroup.createRect({
            x: xs,
            y: ys,
            height: 30,
            width: 250
        }).setFill({
            type: "linear",
            y1: 10,
            y2: 200,
            colors: [
                {
                offset: 0,
                color: randColor()},
           
            {
                offset: 1,
                color: "#4ea1fc"}
            ]
        });

        var nameText = chatGroup.createText({
            x: xs + 10,
            y: ys + 20,
            text: obj.headerName
        }).setFont({
            family: "Arial",
            size: "13pt"
        }).setFill("#FFFFFF");
        // chatGroup.remove(headerRect);
        construct.create("div", {
            id: obj.handleId
        }, "basediv");
        domStyle.set(obj.handleId, {
            "z-index": ++currentZ,
            "position": "absolute",
            "color": "black",
            "height": "30px",
            "width": "230px",
            "top": ys + "px",
            "left": obj.currentLeft + xs + 10 + "px"
        });
        obj.handlepos.l = xs + 10 + "px";
        obj.handlepos.t = ys + "px";
        
        construct.create("div", {
            id: obj.inputId
        }, "basediv"); 
        
        construct.create("div", {
            id: obj.inputId + "history"
        }, "basediv"); 
        
        construct.create("form", {
        	id: obj.formId
        }, obj.inputId); 
        
        
        
        construct.create("input", {
            name: "toUser",
            type: "hidden",
            value: obj.toUser
        }, obj.formId); 
        
        construct.create("textarea", {
            id: obj.inputTextId,
            name: "text" 
        }, obj.formId); 
        
        
        domStyle.set(obj.inputTextId, {
            "height": "36px",
            "width": "230px"
        });
        
        domStyle.set(obj.inputId, {
            "z-index": ++currentZ,
            "position": "absolute",
            "color": "black",
            "top": ys + 190 + "px",
            "left": obj.currentLeft + xs + 10 + "px"
        });
        
        domStyle.set(obj.inputId + "history", {
            "z-index": ++currentZ,
            "position": "absolute",
            "color": "black",
            "height": "160px",
            "width": "250px",
            "top": ys + 30 + "px",
            "left": obj.currentLeft + xs + "px"
        });
        outerStroke.connect("onmousedown", function(e) {
            moveWindowFront();
        });
        dojo.connect(dojo.byId(obj.inputId), "onclick", function(e) {
            moveWindowFront();
        });
        var moverHandle = new dojo.dnd.Moveable(obj.handleId);

        moverHandle.onMouseDown = function(e) {
            this.onDragDetected(e);
            moveWindowFront();
            _event.stop(e);
        }

        var moveWindowFront = function() {
            currentZ += 1;
            domStyle.set(chatSurface.rawNode, {
                "z-index": currentZ
            });
            domStyle.set(obj.svgId, {
                "z-index": ++currentZ
            });
            domStyle.set(obj.handleId, {
                "z-index": ++currentZ
            });
            domStyle.set(obj.inputId, {
                "z-index": ++currentZ
            });
            domStyle.set(obj.inputId + "history", {
                "z-index": ++currentZ
            });
        }
        moverHandle.onMoving = function(mover, shift) {
            var dx = shift.l - obj.handlepos.l;
            var dy = shift.t - obj.handlepos.t;
            obj.handlepos.l = shift.l;
            obj.handlepos.t = shift.t;
            newsvgl = domStyle.get(obj.svgId, "left") + dx;
            newsvgt = domStyle.get(obj.svgId, "top") + dy;
            domStyle.set(obj.svgId, "left", newsvgl + "px");
            domStyle.set(obj.svgId, "top", newsvgt + "px");

            newinputl = domStyle.get(obj.inputId, "left") + dx;
            newinputt = domStyle.get(obj.inputId, "top") + dy;
            domStyle.set(obj.inputId, "left", newinputl + "px");
            domStyle.set(obj.inputId, "top", newinputt + "px");
            
            newHistoryinputl = domStyle.get(obj.inputId + "history", "left") + dx;
            newHistoryinputt = domStyle.get(obj.inputId + "history", "top") + dy;
            domStyle.set(obj.inputId + "history", "left", newHistoryinputl + "px");
            domStyle.set(obj.inputId + "history", "top", newHistoryinputt + "px");
        }
    }

    getRand = function(from, to) {
        return Math.random() * (to - from) + from;
    }

    randColor = function() {
        var red = Math.floor(getRand(0, 255)),
            green = Math.floor(getRand(0, 255)),
            blue = Math.floor(getRand(0, 255)),
            opacity = getRand(0.1, 1);
        return [red, green, blue, opacity];
    }
    
    onMessage = function(m) {
		require([ "dojo" ], function(dojo) {
			console.log(m.data);
			var res = JSON.parse(m.data);
			console.log(res.message);
			console.log(res.window);
			dojo.byId(res.window + "inputhistory").innerHTML += (res.message + "<br/>"); 
		});
	}
	sendMessage = function() {
		var xhr = new XMLHttpRequest();
		xhr.open('POST', '/home/testSend.htm', true);
		xhr.send();
	}
    initialize = function(token) {
	    token = lang.trim(token);
		console.log(' token for this session : ' + token);
		var channel = new goog.appengine.Channel(token);
		console.log('channel created : ' + channel);
		var handler = {
			'onmessage' : onMessage,
			'onopen' : function() {
			},
			'onerror' : function() {
				alert('error occured');
			},
			'onclose' : function() {
			}
		};
		var socket = channel.open(handler);
	}
    
});

